﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

namespace TrafficWatcher.Views.Helpers.TimeVisualizers
{
    class SquareVisualizer : ITimeVisualizer
    {
        private const int ThirtyTwoPixelsForIcon = 32;

        public TimeSpan MaxDuration { get { return TimeSpan.FromHours(3); } }

        public Bitmap GenerateImage(TimeSpan travelTime)
        {
            IList<Color> colorSequence;

            if (travelTime == TimeSpan.Zero)
            {
                travelTime = TimeSpan.FromMinutes(15);
                colorSequence = new List<Color> {Color.DarkGray, Color.LightGray};
            }
            else
            {
                colorSequence = new List<Color>{Color.Green, Color.Yellow, Color.Orange, Color.Red};
            }
            var minutesColor = colorSequence.Last();
                var hoursColor = minutesColor;

                if (travelTime.TotalMinutes < 1.0)
                {
                    travelTime = TimeSpan.FromHours(3);
                }

                var hours = (int) travelTime.TotalHours;

                if (hours < colorSequence.Count - 1)
                {
                    minutesColor = colorSequence[hours + 1];
                    hoursColor = colorSequence[hours];
                }

                //hoursColor = Color.FromArgb(255 - (255*travelTime.Minutes)/60, hoursColor.R, hoursColor.G, hoursColor.B);

            var bitmap = new Bitmap(ThirtyTwoPixelsForIcon, ThirtyTwoPixelsForIcon);

            using (var g = Graphics.FromImage(bitmap))
            using (var hoursBrush = new SolidBrush(hoursColor))
            using (var minutesBrush = new SolidBrush(minutesColor))
            using (var pen = new Pen(Color.Black, 2))
            {
                var r = new Rectangle(-10, -10, ThirtyTwoPixelsForIcon + 20, ThirtyTwoPixelsForIcon + 20);
                g.FillEllipse(hoursBrush, r);
                g.FillPie(minutesBrush, r, 270, travelTime.Minutes * 6); // angle = minutes * 360 degree / 60 minutes

                if (hoursColor != colorSequence.Last())
                {
                    g.DrawPie(pen, r, 270, travelTime.Minutes * 6);
                }
            }

            return bitmap;
        }
    }
}